package com.zkteam.drivertools;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.adapter.Call;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Response;
import com.zkteam.drivertools.adapter.OrderListInfoAdapter;
import com.zkteam.drivertools.api.NetWorkApi;
import com.zkteam.drivertools.bean.OrderInfoList;
import com.zkteam.drivertools.ui.refreshview.XRefreshView;
import com.zkteam.drivertools.utils.SharedPreferenceUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 作者：gaoyin
 * 电话：18810474975
 * 邮箱：18810474975@163.com
 * 版本号：1.0
 * 类描述：   订单信息
 * 备注消息：
 * 修改时间：2017/7/8 下午4:06
 **/
public class MainActivity extends AppCompatActivity {

    protected Unbinder unbinder;
    @BindView(R.id.img_signed)
    ImageView imgSigned;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.img_msg)
    ImageView imgMsg;
    @BindView(R.id.order_content_recyclerview)
    RecyclerView orderContentRecyclerview;
    @BindView(R.id.rtefresh_content)
    XRefreshView rtefreshContent;
    private SVProgressHUD svProgressHUD;

    private OrderListInfoAdapter mOrderListInfoAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);
        imgSigned.setVisibility(View.GONE);
        tvTitle.setText("订单信息");
        svProgressHUD = new SVProgressHUD(this);
        refresh();
        setXrefeshViewConfig();
        mOrderListInfoAdapter = new OrderListInfoAdapter(this);
        orderContentRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        orderContentRecyclerview.setAdapter(mOrderListInfoAdapter);
        rtefreshContent.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
//                延迟500毫秒, 原因 用户体验好 !!!
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                }, 500);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                svProgressHUD.showErrorWithStatus("没有更多数据！");
            }
        });
    }

    private void setXrefeshViewConfig() {
        rtefreshContent.setPinnedTime(2000);
        rtefreshContent.setPullLoadEnable(true);
        rtefreshContent.setPullRefreshEnable(true);
        rtefreshContent.setMoveForHorizontal(true);
        rtefreshContent.setPinnedContent(true);
//        滚动到底部 自动加载数据
        rtefreshContent.setSilenceLoadMore();
    }

    /**
     * 获取数据
     */
    private void refresh() {
        svProgressHUD.showWithStatus("正在加载中...");
        new Thread() {
            @Override
            public void run() {
                String uid = SharedPreferenceUtils.getStringData("uid", "");
                String token = SharedPreferenceUtils.getStringData("token", "");
                String car_no = SharedPreferenceUtils.getStringData("car_no", "");
                Call<String> call = OkGo.<String>get(NetWorkApi.getOrderListApi)
                        .params("uid", uid)
                        .params("token", token)
                        .params("car_no", car_no)
                        .converter(new StringConvert())
                        .adapt();
                call.execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OrderInfoList orderInfoList = new Gson().fromJson(response.body().toString(), OrderInfoList.class);

                        getOrderListInfo(orderInfoList);

                        Log.e("ok", orderInfoList.toString());
                    }

                    /**
                     *  服务器错误
                     * @param response
                     */
                    @Override
                    public void onError(Response<String> response) {
                        getOrderInfoError();
                        super.onError(response);
                    }

                });
            }
        }.start();
    }

    private void getOrderInfoError() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                svProgressHUD.dismissImmediately();
                svProgressHUD.showErrorWithStatus("网络错误，请重试！");
            }
        });
    }

    /**
     * 订单信息列表
     *
     * @param orderInfoList
     */
    private void getOrderListInfo(final OrderInfoList orderInfoList) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                svProgressHUD.dismissImmediately();
                if (rtefreshContent != null) {
                    rtefreshContent.stopRefresh();
                }
                if (orderInfoList.getBaseResponse().getRet() == 0) {
                    SharedPreferenceUtils.setStringData("token", orderInfoList.getToken());
                    mOrderListInfoAdapter.getOrderInfo(orderInfoList.getOrderList());
                }
            }
        });
    }

    @OnClick(R.id.img_msg)
    public void userInfo() {
        startActivity(new Intent(this, UserInfoActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null)
            unbinder.unbind();
    }
}
